#!/bin/sh

# Multi-Gen LRU
if [ -z $(uci -q get cpufreq.cpufreq.mglru_enabled) ]; then
	uci -q set cpufreq.cpufreq.mglru_enabled="1"
	uci -q set cpufreq.cpufreq.mglru_min_ttl_ms="1000"
	uci -q commit cpufreq
fi

# Cpufreq
if [ -z $(uci -q get cpufreq.cpufreq.governor0) ]; then

uci_write_config() {
	uci -q set cpufreq.cpufreq.governor$1="$2"
	uci -q set cpufreq.cpufreq.minfreq$1="$3"
	uci -q set cpufreq.cpufreq.maxfreq$1="$4"
	[ -n "$5" ] && uci -q set cpufreq.cpufreq.sdfactor$1="$5"
	[ -n "$6" ] && uci -q set cpufreq.cpufreq.upthreshold$1="$6"
	uci -q commit cpufreq
}

CPU_FREQS="$(cat '/sys/devices/system/cpu/cpufreq/policy0/scaling_available_frequencies')"
CPU_POLICYS="$(find '/sys/devices/system/cpu/cpufreq/policy'* -maxdepth 0 | grep -Eo '[0-9]+')"
source "/etc/openwrt_release"
case "$DISTRIB_TARGET" in
	"rockchip/armv8")
		uci_write_config 0 schedutil $(echo $CPU_FREQS | awk '{print $2}') $(echo $CPU_FREQS | awk '{print $NF}')
		# big.Little
		if echo "$CPU_POLICYS" | grep -q "4"; then
			CPU_FREQS_PERFORMANCE="$(cat "/sys/devices/system/cpu/cpufreq/policy${CPU_POLICYS}/scaling_available_frequencies")"
			uci_write_config 4 schedutil $(echo $CPU_FREQS_PERFORMANCE | awk '{print $2}') $(echo $CPU_FREQS_PERFORMANCE | awk '{print $NF}')
		fi
		;;
esac

fi

[ -f "/etc/config/ucitrack" ] && {
uci -q batch <<-EOF >/dev/null
	delete ucitrack.@cpufreq[-1]
	add ucitrack cpufreq
	set ucitrack.@cpufreq[-1].init=cpufreq
	commit ucitrack
EOF
}

rm -f /tmp/luci-indexcache*
exit 0
